// 语音增强音频对比控制功能
export function initAudioControls() {
  // 存储所有音频元素的引用
  const audioElements = new Map();
  let currentPlayingButton = null;
  let currentAudio = null;
  let currentMuteButton = null;

  // 格式化时间显示
  function formatTime(seconds) {
    if (isNaN(seconds)) return '0:00';
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  }

  // 创建音频元素
  function createAudioElement(audioFile, audioData = null, playButton = null) {
    // 如果已经创建过，直接返回
    const cacheKey = audioData || audioFile;
    if (audioElements.has(cacheKey)) {
      return audioElements.get(cacheKey);
    }

    let audio;
    if (audioData) {
      // 从上传的数据创建音频
      audio = new Audio(audioData);
    } else {
      // 从文件路径创建音频
      const audioPath = `/audio/${audioFile}`;
      audio = new Audio(audioPath);
    }
    audio.preload = 'metadata';
    
    // 设置音频事件监听器
    audio.addEventListener('ended', () => {
      resetButtonState(currentPlayingButton);
      currentPlayingButton = null;
      currentAudio = null;
      currentMuteButton = null;
    });

    audio.addEventListener('error', (e) => {
      console.warn(`音频文件加载失败: ${audioFile || 'uploaded audio'}`, e);
      resetButtonState(currentPlayingButton);
      currentPlayingButton = null;
      currentAudio = null;
      currentMuteButton = null;
    });

    audio.addEventListener('timeupdate', () => {
      updateTimeDisplayForButton(playButton || currentPlayingButton);
    });

    audio.addEventListener('loadedmetadata', () => {
      updateTimeDisplayForButton(playButton || currentPlayingButton);
    });

    audioElements.set(cacheKey, audio);
    return audio;
  }

  // 更新按钮状态
  function updateButtonState(button, isPlaying) {
    if (!button) return;
    
    const playIcon = button.querySelector('.play-icon');
    
    if (isPlaying) {
      button.setAttribute('data-playing', 'true');
      button.classList.add('playing');
      if (playIcon) playIcon.style.display = 'none';
    } else {
      button.setAttribute('data-playing', 'false');
      button.classList.remove('playing');
      if (playIcon) playIcon.style.display = 'block';
    }
  }

  // 重置按钮状态
  function resetButtonState(button) {
    if (!button) return;
    updateButtonState(button, false);
    resetTimeDisplay(button);
  }

  // 通过按钮更新时间显示（适用于所有类型的音频）
  function updateTimeDisplayForButton(button) {
    if (!button || !currentAudio) return;

    const audioPlayer = button.closest('.audio-player');
    if (!audioPlayer) return;

    const currentTimeSpan = audioPlayer.querySelector('.current-time');
    const totalTimeSpan = audioPlayer.querySelector('.total-time');

    if (currentTimeSpan) {
      currentTimeSpan.textContent = formatTime(currentAudio.currentTime);
    }

    if (totalTimeSpan && currentAudio.duration) {
      totalTimeSpan.textContent = formatTime(currentAudio.duration);
    }
  }

  // 更新时间显示（保留用于兼容性）
  function updateTimeDisplay(audioFile) {
    const audio = audioElements.get(audioFile);
    if (!audio) return;

    // 找到对应的播放器容器
    const playButton = document.querySelector(`[data-audio="${audioFile}"]`);
    if (!playButton) return;

    const audioPlayer = playButton.closest('.audio-player');
    if (!audioPlayer) return;

    const currentTimeSpan = audioPlayer.querySelector('.current-time');
    const totalTimeSpan = audioPlayer.querySelector('.total-time');

    if (currentTimeSpan) {
      currentTimeSpan.textContent = formatTime(audio.currentTime);
    }

    if (totalTimeSpan && audio.duration) {
      totalTimeSpan.textContent = formatTime(audio.duration);
    }
  }

  // 重置时间显示
  function resetTimeDisplay(button) {
    if (!button) return;

    const audioPlayer = button.closest('.audio-player');
    if (!audioPlayer) return;

    const currentTimeSpan = audioPlayer.querySelector('.current-time');
    const totalTimeSpan = audioPlayer.querySelector('.total-time');

    if (currentTimeSpan) {
      currentTimeSpan.textContent = '0:00';
    }
    if (totalTimeSpan) {
      totalTimeSpan.textContent = '0:00';
    }
  }

  // 更新静音按钮状态
  function updateMuteButtonState(muteButton, isMuted) {
    if (!muteButton) return;
    
    const muteIcon = muteButton.querySelector('.mute-icon');
    
    if (isMuted) {
      muteButton.classList.add('muted');
      if (muteIcon) muteIcon.style.display = 'none';
    } else {
      muteButton.classList.remove('muted');
      if (muteIcon) muteIcon.style.display = 'block';
    }
  }

  // 停止当前播放的音频
  function stopCurrentAudio() {
    if (currentAudio && !currentAudio.paused) {
      currentAudio.pause();
      currentAudio.currentTime = 0;
    }
    
    if (currentPlayingButton) {
      resetButtonState(currentPlayingButton);
      currentPlayingButton = null;
    }
    
    if (currentMuteButton) {
      updateMuteButtonState(currentMuteButton, false);
      currentMuteButton = null;
    }
    
    currentAudio = null;
  }

  // 静音/取消静音
  function toggleMute(muteButton) {
    const audioFile = muteButton.getAttribute('data-audio');
    const audioData = muteButton.getAttribute('data-audio-data');
    
    // 获取音频元素
    const cacheKey = audioData || audioFile;
    const audio = audioElements.get(cacheKey);
    
    if (!audio) {
      console.warn('音频文件未找到');
      return;
    }

    const isMuted = audio.muted;
    audio.muted = !isMuted;
    
    updateMuteButtonState(muteButton, !isMuted);
    
    // 如果是当前播放的音频，更新当前静音按钮引用
    if (currentAudio === audio) {
      currentMuteButton = !isMuted ? muteButton : null;
    }
    
    console.log(`${isMuted ? '取消静音' : '静音'}: ${audioFile || 'uploaded audio'}`);
  }

  // 播放音频
  function playAudio(button) {
    const audioFile = button.getAttribute('data-audio');
    const audioData = button.getAttribute('data-audio-data'); // 上传的音频数据
    const sample = button.getAttribute('data-sample');
    const type = button.getAttribute('data-type');
    
    if (!audioFile && !audioData) {
      console.warn('音频文件未指定');
      return;
    }

    // 如果点击的是当前播放的按钮，则暂停
    if (currentPlayingButton === button && currentAudio && !currentAudio.paused) {
      currentAudio.pause();
      resetButtonState(button);
      currentPlayingButton = null;
      currentAudio = null;
      return;
    }

    // 停止当前播放的音频
    stopCurrentAudio();

    // 创建或获取音频元素（传递按钮用于时间显示更新）
    const audio = createAudioElement(audioFile, audioData, button);
    
    // 设置加载状态
    button.classList.add('loading');
    
    // 播放音频
    const playPromise = audio.play();
    
    if (playPromise !== undefined) {
      playPromise.then(() => {
        // 播放成功
        button.classList.remove('loading');
        updateButtonState(button, true);
        currentPlayingButton = button;
        currentAudio = audio;
        
        // 找到对应的静音按钮
        const audioPlayer = button.closest('.audio-player');
        const muteButton = audioPlayer ? audioPlayer.querySelector('.audio-mute-btn') : null;
        if (muteButton) {
          currentMuteButton = muteButton;
          // 确保静音按钮状态正确
          updateMuteButtonState(muteButton, audio.muted);
        }
        
        // 立即更新时间显示
        updateTimeDisplayForButton(button);
        
        console.log(`播放音频: 样本${sample} - ${type} (${audioFile || 'uploaded audio'})`);
      }).catch(error => {
        // 播放失败
        button.classList.remove('loading');
        console.error('音频播放失败:', error);
        
        // 显示用户友好的错误信息
        if (error.name === 'NotAllowedError') {
          console.warn('用户需要先与页面交互才能播放音频');
        } else {
          console.warn(`音频文件可能不存在: ${audioFile || 'uploaded audio'}`);
        }
      });
    }
  }

  // 批量播放同一行的音频（用于对比）
  function playRowComparison(button) {
    const row = button.closest('tr');
    const sample = button.getAttribute('data-sample');
    
    // 获取同一行所有音频按钮
    const audioButtons = row.querySelectorAll('.audio-play-btn');
    
    // 停止当前播放
    stopCurrentAudio();
    
    // 播放第一个可用的音频
    for (let btn of audioButtons) {
      const audioFile = btn.getAttribute('data-audio');
      if (audioFile) {
        playAudio(btn);
        break;
      }
    }
  }

  // 键盘快捷键支持
  function handleKeyboardShortcuts(event) {
    // 按空格键暂停/播放当前音频
    if (event.code === 'Space' && currentAudio) {
      event.preventDefault();
      if (currentAudio.paused) {
        currentAudio.play();
      } else {
        currentAudio.pause();
      }
    }
    
    // 按M键切换静音
    if (event.code === 'KeyM' && currentAudio && currentMuteButton) {
      event.preventDefault();
      toggleMute(currentMuteButton);
    }
    
    // 按Escape键停止播放
    if (event.code === 'Escape') {
      stopCurrentAudio();
    }
  }

  // 初始化音频控制
  function initAudioButtons() {
    // 绑定播放按钮事件
    document.querySelectorAll('.audio-play-btn').forEach(button => {
      button.addEventListener('click', (e) => {
        e.preventDefault();
        playAudio(button);
      });
      
      // 添加键盘支持
      button.setAttribute('tabindex', '0');
      button.addEventListener('keydown', (e) => {
        if (e.code === 'Enter' || e.code === 'Space') {
          e.preventDefault();
          playAudio(button);
        }
      });
    });

    // 绑定静音按钮事件
    document.querySelectorAll('.audio-mute-btn').forEach(button => {
      button.addEventListener('click', (e) => {
        e.preventDefault();
        toggleMute(button);
      });
      
      // 添加键盘支持
      button.setAttribute('tabindex', '0');
      button.addEventListener('keydown', (e) => {
        if (e.code === 'Enter' || e.code === 'Space') {
          e.preventDefault();
          toggleMute(button);
        }
      });
    });
  }

  // 添加音频统计信息
  function logAudioStats() {
    const totalPlayButtons = document.querySelectorAll('.audio-play-btn').length;
    const totalMuteButtons = document.querySelectorAll('.audio-mute-btn').length;
    const totalSamples = new Set(
      Array.from(document.querySelectorAll('.audio-play-btn'))
        .map(btn => btn.getAttribute('data-sample'))
    ).size;
    
    console.log(`音频对比系统已初始化:`);
    console.log(`  - ${totalPlayButtons}个播放按钮`);
    console.log(`  - ${totalMuteButtons}个静音按钮`);
    console.log(`  - ${totalSamples}个样本`);
    console.log(`  - 支持键盘快捷键: 空格键(播放/暂停), M键(静音), Escape键(停止)`);
  }

  // 初始化功能
  function init() {
    initAudioButtons();
    document.addEventListener('keydown', handleKeyboardShortcuts);
    
    // 页面卸载时停止所有音频
    window.addEventListener('beforeunload', stopCurrentAudio);
    
    // 页面隐藏时暂停音频
    document.addEventListener('visibilitychange', () => {
      if (document.hidden && currentAudio && !currentAudio.paused) {
        currentAudio.pause();
      }
    });
    
    logAudioStats();
  }

  // 启动初始化
  init();

  // 监听动态更新事件（用于上传新音频后重新绑定）
  document.addEventListener('audio-controls-update', () => {
    console.log('检测到音频控件更新，重新初始化...');
    initAudioButtons();
  });
}
